package com.sky.task;

import com.sky.client.OrderMapperClient;
import com.sky.entity.Orders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    OrderMapperClient orderMapperClient;
    
    //每分钟触发一次
//    @Scheduled(cron = "0 0/1 * * * ?")
//    @Scheduled(cron = "10/15 * * * * ?")
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void processTimeoutOrder(){
        log.info("处理超时订单：{}", LocalDateTime.now());
        //查询距离当前时间15分钟内待支付的订单
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);//15分钟前的时间
         List<Orders> ordersList =orderMapperClient.getByStatusAndOrdertimeLT( Orders.PENDING_PAYMENT, time);
         if(ordersList != null && ordersList.size() > 0){
             for (Orders orders : ordersList) {
                 orders.setStatus(Orders.CANCELLED);
                 orders.setCancelReason("支付超时，自动取消");
                 orders.setCancelTime(LocalDateTime.now());
                 orderMapperClient.update(orders);
             }
         }
    }
    /**
     * 处理“派送中”状态的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "5/15 * * * * ?")
    public void processDeliveryOrder(){
        log.info("处理派送中订单：{}", LocalDateTime.now());
        // select * from orders where status = 4 and order_time < 当前时间-1小时
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapperClient.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS, time);

        if(ordersList != null && ordersList.size() > 0){
            ordersList.forEach(order -> {
                order.setStatus(Orders.COMPLETED);
                orderMapperClient.update(order);
            });
        }
    }
}